package com.zn.controller;

import com.zn.common.constants.Constants;
import com.zn.common.resp.ApiResult;
import com.zn.common.utils.FileUtils;
import com.zn.pojo.MhyMedia;
import com.zn.pojo.VeiReportInfo;
import com.zn.pojo.android.*;
import com.zn.services.MhyService;
import com.zn.services.VeiReportInfoService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @author xyl
 * @create 2020-09-09 14:16
 * @desc 用于和安卓对接上传报告数据实体类
**/
@Controller
@RequestMapping("mhy")
@Log4j2
public class MhyController {

    @Autowired
    private MhyService mhyService;
    @Autowired
    private VeiReportInfoService veiReportInfoService;

    /**
     * 上传 获得检测流水号实体类
     * @param processNo
     * @return
     */
    @PostMapping("/et/process")
    @ResponseBody
    public ApiResult process(@RequestBody ProcessNo processNo){
        int count = mhyService.addProcess(processNo);
        //TODO 生成报告
        VeiReportInfo info =  veiReportInfoService.getReportByUUId(processNo.getUuid());
        if(ObjectUtils.isEmpty(info)){
            log.error("无法对应到数据uuid:"+processNo);
            return new ApiResult();
        }
        info.setCheckDate(processNo.getEtDate());
        info.setCheckMethod(processNo.getEtMethod().contains("速")?"自由加速法":"自由加载法");
        info.setEngineSpeed(processNo.getEtRpm());
        info.setBanBlowdownRegion(processNo.getEtRestricted().contains("不")?"否":"是");
        info.setEquipmentModel(processNo.getSmokeMeterManu());
        info.setEquipmentFactoryNumber(processNo.getSmokeMeterNo());
        info.setMachineProtectionNumber(processNo.getMhyPlate());
        veiReportInfoService.modifyReportByRid(info);
        return new ApiResult();
    }

    /**
     * 上传检测过程数据
     * @param processData
     * @return
     */
    @PostMapping("/et/process/data/batch")
    @ResponseBody
    public ApiResult batch(@RequestBody List<ProcessData> processData){
        int count = mhyService.addProcessBatchList(processData);
        return new ApiResult();
    }

    /**
     * 上传检测结果实体类
     * @param smokeDetection
     * @return
     */
    @PostMapping("/et/result")
    @ResponseBody
    public ApiResult result(@RequestBody SmokeDetection smokeDetection){
        int count = 0;
        if(!StringUtils.isEmpty(smokeDetection.getUuid())){
            SmokeDetection temp = mhyService.getSmokeDetectionInfoByUUId(smokeDetection.getUuid());
            if(ObjectUtils.isEmpty(temp)){
                count = mhyService.addResult(smokeDetection);
            }else{
                smokeDetection.setSmokeDetectionId(temp.getSmokeDetectionId());
                mhyService.modifySmokeDetectionByKey(smokeDetection);
            }
        }
        //todo 生成报告
        VeiReportInfo info =  veiReportInfoService.getReportByUUId(smokeDetection.getUuid());
        if(ObjectUtils.isEmpty(info)){
            log.error("无法对应到数据uuid:"+smokeDetection);
            return new ApiResult();
        }
        info.setAmbientTemperature(smokeDetection.getEtTemperature());
        info.setAltitude(smokeDetection.getEtElevation());
        info.setAmbientHumidity(smokeDetection.getEtHumidity());
        info.setAtmosphericPressure(smokeDetection.getEtElevation());
        info.setCheckStartTime(smokeDetection.getEtFrom());
        info.setCheckEndTime(smokeDetection.getEtTo());
        info.setCheckPlace(smokeDetection.getEtLocation());
        info.setCheckResult1(smokeDetection.getEtSmoke());
        info.setCheckResult2(smokeDetection.getEtSmokeNd());
        info.setCheckResult3(smokeDetection.getEtSmokeRd());
        info.setCheckEngineSpeed(smokeDetection.getEtRpm());
        try {
            info.setVisualPlume(smokeDetection.getEtVisualPlume().contains("不可见")?0:1);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        info.setResultJudgment(smokeDetection.get());
        veiReportInfoService.modifyReportByRid(info);
        return new ApiResult();
    }


    /**
     * 上传检测结果照片  弃用 , 和上传检测过程图片结合
     * @param vri
     * @return
     */
    @Deprecated
    @PostMapping("/et/image/upload")
    @ResponseBody
    public ApiResult imageResultUpload(@RequestBody @Validated VehicleResultImage vri){
        int count;
        String uuid = null;
        MhyMedia mm =  mhyService.getMhyMediaByProcessNo(vri.getProcessNo());
        vri.setFileData(FileUtils.Base64ToImage(vri.getFileData()));
        if(ObjectUtils.isEmpty(mm)){
            SmokeDetection sd =  mhyService.getSmokeDetectionInfoByProcessNo(vri.getProcessNo());
            if(ObjectUtils.isEmpty(sd)){
                count = mhyService.addMhyMedia(vri);
            }else{
                uuid = sd.getUuid();
                MhyMedia media =  mhyService.getMhyMediaByUUId(uuid);
                if(ObjectUtils.isEmpty(media)){
                    count = mhyService.addMhyMedia(vri);
                }else{
                    count = mhyService.modifyMhyMedia(vri,media.getMediaId());
                }
            }
        }else{
            count = mhyService.modifyMhyMedia(vri,vri.getProcessNo());
        }
        //todo 生成报告
        if(count == 0){
            return new ApiResult(500,"上传错误, 请对照字段");
        }else{
            if(!StringUtils.isEmpty(uuid)){
                VeiReportInfo info = veiReportInfoService.getReportByUUId(uuid);
                if(!ObjectUtils.isEmpty(info)){
                    VehicleImage vehicleImage = new VehicleImage();
                    vehicleImage.setFileData(vri.getFileData());
                    vehicleImage.setFilename(vri.getFilename());
                    vehicleImage.setUuid(uuid);
                    int count2 = veiReportInfoService.modifyAndroidReportImage(info,vehicleImage);
                }
            }
        }
        return new ApiResult();
    }
    /**
     * 上传检测结果视频
     * @param file
     * @return
     */
    @PostMapping("/et/video/upload")
    @ResponseBody
    public ApiResult videoUpload(@RequestParam String processNo, MultipartFile file){
        MhyMedia mm =  mhyService.getMhyMediaByProcessNo(processNo);
        if (ObjectUtils.isEmpty(mm)) {
            return new ApiResult(500,"此流水号无效!");
        }
        InputStream inputStream;
        OutputStream os;
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            byte[] bs = new byte[1024];
            int len;
            inputStream = file.getInputStream();
            File tempFile = new File(Constants.REPORT_VIDEO_LOCAL_URL);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + uuid+".mp4");
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        int count = mhyService.modifyMhyMediaVideoByProcessNo(processNo,uuid+".mp4");
        return new ApiResult();
    }
}
